<template>
  <!-- 项目申报页面 -->
  <!-- 包含两部分   1. 基本信息  2. 项目明细-->
  <view>
    <u-navbar
      v-if="!$isWeixin()"
      :title="title"
      :titleBold="true"
      :background="{ backgroundColor: '#ffffff' }"
      :is-fixed="true"
    ></u-navbar>

    <view class="nav-list">
      <u-tabs :list="navlist" active-color="#f47021" :is-scroll="false" :current="navIndex" @change="change"></u-tabs>
    </view>
    <view class="u-m-l-20 u-m-r-20 current0" v-show="navIndex == 0">
      <u-cell-group>
        <u-cell-item title="年份" :arrow="false">{{ form.Year }}</u-cell-item>
        <u-cell-item title="月份" :arrow="false">{{ form.MonthId }}月</u-cell-item>
        <u-cell-item title="大区" :arrow="false">
          <u-input
            placeholder="请选择大区"
            input-align="right"
            type="select"
            v-model="form.Region_Area"
            :select-open="showAreaPicker"
            @tap="showAreaPicker = true"
          ></u-input>
          <!-- <text v-else>{{ form.Region_Area }}</text> -->
        </u-cell-item>
      </u-cell-group>
    </view>
    <view class="current1 u-p-20" v-show="navIndex == 1">
      <view class=" u-m-t-20" style="text-align: right;" v-if="form.PostType != 2">
        <!-- <view class="current1-title"><span class="line"></span></view> -->
        <u-button type="warning" size="mini" @click="addProject">添加项目</u-button>
      </view>
      <view class="project-wrapper">
        <u-tabs-swiper
          ref="uTabs"
          :show-bar="false"
          :list="form.DetailList"
          :current="projectIndex"
          @change="handleProjectChange"
          :is-scroll="true"
          swiperWidth="750"
          name="tab_name"
        ></u-tabs-swiper>

        <swiper class="swiper-box" :current="swiperIndex" @transition="transition" @animationfinish="animationfinish">
          <swiper-item class="swiper-item" v-for="(item, index) in form.DetailList" :key="index">
            <scroll-view scroll-y style="height: 100%;width: 100%;">
              <view class="u-flex u-row-between" style="margin-top: 20rpx;">
                <div class="tab-title" style="margin-top: 0;margin-bottom: 0;">
                  <text class="u-m-r-10">项目信息</text>
                  <u-icon name="tags"></u-icon>
                </div>
                <view>
                  <u-button v-if="form.PostType != 2" type="error" size="mini" @tap="handleDeleteClick(index)">
                    删除项目
                  </u-button>
                </view>
              </view>
              <u-cell-group class=" u-m-t-20">
                <u-cell-item
                  required
                  label="费用类型"
                  :arrow="false"
                  :border-bottom="false"
                  style="padding-bottom: 0;"
                ></u-cell-item>
                <view label="" :arrow="false" style="padding-left: 20rpx;">
                  <u-cell-item label="费用主体" :arrow="false" style="padding-bottom: 10rpx;">
                    <u-input
                      type="select"
                      :value="
                        Base_Apply_WaysType_List[item.wayTypeIndex] && Base_Apply_WaysType_List[item.wayTypeIndex].Value
                      "
                      placeholder="费用主体"
                      input-align="right"
                      @tap="item.showWayTypePicker = true"
                    ></u-input>
                  </u-cell-item>
                  <u-cell-item label="费用类型" :arrow="false" style="padding-bottom: 10rpx;">
                    <u-input
                      type="select"
                      :value="moneyTypeList[item.moneyTypeIndex] && moneyTypeList[item.moneyTypeIndex].Value"
                      placeholder="费用类型"
                      input-align="right"
                      @tap="item.showMoneyTypePicker = true"
                    ></u-input>
                  </u-cell-item>
                  <u-cell-item label="活动类型" :arrow="false" style="padding-bottom: 10rpx;" :border-bottom="false">
                    <u-input
                      type="select"
                      :value="
                        activityTypeList[item.activityTypeIndex] && activityTypeList[item.activityTypeIndex].Value
                      "
                      placeholder="活动类型"
                      input-align="right"
                      @tap="item.showActivityTypePicker = true"
                    ></u-input>
                  </u-cell-item>
                </view>

                <u-cell-item label="项目名称" :arrow="false" required>
                  <u-input v-model="item.Title" placeholder="项目名称" input-align="right"></u-input>
                </u-cell-item>
                <u-cell-item label="计划开始时间" :arrow="false" required>
                  <u-input
                    v-model="item.StartTime_Str"
                    type="select"
                    placeholder="计划开始时间"
                    input-align="right"
                    :select-open="item.showStart"
                    @click="item.showStart = true"
                  ></u-input>

                  <u-calendar
                    class="calendar"
                    safe-area-inset-bottom
                    v-model="item.showStart"
                    mode="date"
                    max-date="2100-01-01"
                    btn-type="warning"
                    active-bg-color="#F19D38"
                    @change="handleStartTimeChange($event, item)"
                  ></u-calendar>
                </u-cell-item>
                <u-cell-item label="计划结束时间" :arrow="false" required>
                  <u-input
                    v-model="item.EndTime_Str"
                    type="select"
                    placeholder="计划结束时间"
                    input-align="right"
                    :select-open="item.showEnd"
                    @click="item.showEnd = true"
                  ></u-input>

                  <u-calendar
                    class="calendar"
                    v-model="item.showEnd"
                    safe-area-inset-bottom
                    mode="date"
                    max-date="2100-01-01"
                    btn-type="warning"
                    active-bg-color="#F19D38"
                    @change="handleEndTimeChange($event, item)"
                  ></u-calendar>
                </u-cell-item>

                <u-cell-item
                  title="项目描述"
                  required
                  :arrow="false"
                  :border-bottom="false"
                  style="padding-bottom: 0;"
                ></u-cell-item>
                <u-cell-item title="" :arrow="false"><u-input v-model="item.Remark" type="textarea" /></u-cell-item>
              </u-cell-group>

              <div class="tab-title">
                <text class="u-m-r-10">具体信息</text>
                <u-icon name="tags"></u-icon>
              </div>

              <u-cell-group>
                <u-cell-item label="推广品牌" :arrow="false" required>
                  <u-radio-group v-model="item.Brand" @change="handleBrandChange($event, item)">
                    <view class="grid-2">
                      <u-radio v-for="(brand, b_index) in item.Base_Brand_List" :key="b_index" :name="brand.Value">
                        {{ brand.Value }}
                      </u-radio>
                    </view>
                  </u-radio-group>
                </u-cell-item>
                <u-cell-item label="落地城市" :arrow="false" required>
                  <city-select v-model="item.areaCode" @city-change="handleCityChange($event, item)"></city-select>
                  <u-input v-model="item.Address" inputAlign="right" placeholder="详细地址"></u-input>
                </u-cell-item>

                <u-cell-item label="申请对象" :arrow="false" required>
                  <u-radio-group v-model="item.ObjectTypeId">
                    <view class="grid-2">
                      <u-radio v-for="(obj, obj_index) in applyObjectList" :key="obj_index" :name="obj.value">
                        {{ obj.label }}
                      </u-radio>
                    </view>
                  </u-radio-group>
                </u-cell-item>

                <dealer-select
                  v-if="item.ObjectTypeId != 99"
                  class="dealer-select"
                  ref="dealerSelectForm"
                  @first-change="onFirstDealerChange(arguments, item)"
                  @second-change="onSecondDealerChange($event, item)"
                  @change="onStoreDealerChange($event, item)"
                  :FirstDealerId="item.FirstDealerId"
                  :SecondDealerId="item.DoubleDealerId"
                  :StoreDealerId="item.DoorDealerId"
                  :show-second="item.ObjectTypeId > 1"
                  :show-store="item.ObjectTypeId > 2"
                ></dealer-select>

                <block v-else>
                  <u-cell-item
                    title="其他对象"
                    required
                    :arrow="false"
                    :border-bottom="false"
                    style="padding-bottom: 0;"
                  ></u-cell-item>
                  <u-cell-item title="" :arrow="false">
                    <u-input v-model="item.ObjectOther" type="textarea" />
                  </u-cell-item>
                </block>

                <u-cell-item
                  title="点位/场次"
                  required
                  :arrow="false"
                  :border-bottom="false"
                  style="padding-bottom: 0;"
                ></u-cell-item>
                <u-cell-item title="" :arrow="false"><u-input v-model="item.Position" type="textarea" /></u-cell-item>

                <u-cell-item
                  title="具体形式-活动投放"
                  required
                  :arrow="false"
                  :border-bottom="false"
                  style="padding-bottom: 0;"
                ></u-cell-item>
                <u-cell-item title="" :arrow="false"><u-input v-model="item.Mode" type="textarea" /></u-cell-item>

                <div class="tab-title">
                  <text class="u-m-r-10">费用信息</text>
                  <u-icon name="tags"></u-icon>
                </div>

                <u-cell-item title="BDR预算" required :arrow="false">
                  <u-input placeholder="BDR预算" v-model="item.BDRCost" type="number" input-align="right"></u-input>
                </u-cell-item>
                <u-cell-item title="一级预算" required :arrow="false">
                  <u-input placeholder="一级预算" v-model="item.FirstCost" type="number" input-align="right"></u-input>
                </u-cell-item>
                <u-cell-item title="二级预算" required :arrow="false">
                  <u-input placeholder="二级预算" v-model="item.DoubleCost" type="number" input-align="right"></u-input>
                </u-cell-item>
                <u-cell-item title="总计预算" required :arrow="false">
                  {{ Number(item.BDRCost) + Number(item.FirstCost) + Number(item.DoubleCost) }}
                </u-cell-item>

                <u-cell-item
                  title="申请理由"
                  required
                  :arrow="false"
                  :border-bottom="false"
                  style="padding-bottom: 0;"
                ></u-cell-item>
                <u-cell-item title="" :arrow="false">
                  <u-input v-model="item.ApplyReason" type="textarea" />
                </u-cell-item>
              </u-cell-group>
            </scroll-view>
          </swiper-item>
        </swiper>
      </view>
    </view>
    <div class="current1 u-p-20" v-show="navIndex == 2">
      <view class="current1-content u-p-20" v-for="(item, index) in prolist" v-show="proIndex == index">
        <u-form class="form" :model="{}" :label-width="180">
          <div class="tab-title u-m-t-20">
            <text class="u-m-r-10">核销信息</text>
            <u-icon name="tags"></u-icon>
          </div>
          <view class="u-p-l-10">
            <u-form-item label="标题信息"><u-upload></u-upload></u-form-item>
            <u-form-item label="标题信息"><u-upload></u-upload></u-form-item>
            <u-form-item label="标题信息"><u-upload></u-upload></u-form-item>
          </view>
          <div class="tab-title">
            <text class="u-m-r-10">核销备注</text>
            <u-icon name="tags"></u-icon>
          </div>
          <view class="u-m-b-40"><u-input type="textarea" :border="true" /></view>
        </u-form>
      </view>
    </div>

    <view class="btn-group-fixed u-p-20"><u-button type="warning" @click="handleCommit">提交</u-button></view>

    <u-toast ref="uToast" />

    <u-modal
      v-model="showConfirm"
      ref="confirmRef"
      :async-close="true"
      :show-title="false"
      content="是否确认删除"
      :show-cancel-button="true"
      @confirm="handleDeleteProject"
    ></u-modal>

    <u-select
      :default-value="[companyIndex]"
      @confirm="onCompanyChange"
      v-model="showCompanyPicker"
      :list="Base_Apply_BudGetList"
      label-name="Value"
      value-name="Key"
      safe-area-inset-bottom
    ></u-select>

    <u-select
      :default-value="[areaIndex]"
      @confirm="onAreaChange"
      v-model="showAreaPicker"
      :list="Base_Apply_Region_AreaList"
      label-name="Value"
      value-name="Key"
      safe-area-inset-bottom
    ></u-select>

    <u-select
      :default-value="[villageAreaIndex]"
      @confirm="onVillageAreaChange"
      v-model="showVillageAreaPicker"
      :list="Base_Apply_Village_AreaList"
      label-name="Value"
      value-name="Key"
      safe-area-inset-bottom
    ></u-select>

    <template v-if="form.DetailList.length > 0">
      <u-select
        :default-value="[form.DetailList[projectIndex].wayTypeIndex]"
        @confirm="onWayTypeChange"
        v-model="form.DetailList[projectIndex].showWayTypePicker"
        :list="Base_Apply_WaysType_List"
        label-name="Value"
        value-name="Key"
        safe-area-inset-bottom
      ></u-select>

      <u-select
        :default-value="[form.DetailList[projectIndex].moneyTypeIndex]"
        @confirm="onMoneyTypeChange"
        v-model="form.DetailList[projectIndex].showMoneyTypePicker"
        :list="moneyTypeList"
        label-name="Value"
        value-name="Key"
        safe-area-inset-bottom
      ></u-select>

      <u-select
        :default-value="[form.DetailList[projectIndex].activityTypeIndex]"
        @confirm="onActivityTypeChange"
        v-model="form.DetailList[projectIndex].showActivityTypePicker"
        :list="activityTypeList"
        label-name="Value"
        value-name="Key"
        safe-area-inset-bottom
      ></u-select>
    </template>

    <u-popup v-model="showSupportPopup" mode="bottom" height="60%" :border-radius="24" closeable>
      <u-card :border="false" :title="supportPopupTitle">
        <view slot="body">
          <view
            class="u-body-item u-flex u-border-bottom u-col-between u-p-t-0"
            v-for="(item, index) in supportPackageList"
            :key="index"
          >
            <view style="width: 400rpx" class="u-flex u-row-center">
              <u-image :src="$getImageUrl(item.Value_T)" mode="widthFix" :width="400"></u-image>
            </view>
            <view class="u-body-item-title u-line-2">{{ item.Value }}</view>
          </view>
        </view>
      </u-card>
    </u-popup>
  </view>
</template>

<script>
import { getTimeByDateString } from '@/common/dateUtils';

export default {
  data() {
    return {
      title: '预测申报',

      navlist: [
        {
          name: '基本信息'
        },
        {
          name: '项目明细'
        }
        // {
        //   name: '核销信息'
        // }
      ],
      navIndex: 0,
      prolist: [
        {
          name: '项目_1',
          form: {}
        }
      ],
      proIndex: 0,
      isOpen: false,

      quarterMap: {
        1: '第一季度',
        2: '第二季度',
        3: '第三季度',
        4: '第四季度'
      },

      applyObjectList: [
        { label: '一级', value: 1, checked: false },
        { label: '二级', value: 2, checked: false },
        { label: '门店', value: 3, checked: false },
        { label: '其他', value: 99, checked: false }
      ],

      quarter: '',

      month: '',

      DetailId: '',

      showConfirm: false,

      // 主体列表
      Base_Apply_BudGetList: [],

      // 大区列表
      Base_Apply_Region_AreaList: [],

      // 团队区域列表
      Base_Apply_Village_AreaList: [],

      //
      Base_Apply_OtherSupper_List: [],

      // 品牌列表
      Base_Brand_List: [],

      // 线上线下方式 类型
      Base_Apply_WaysType_List: [],
      // 费用类型
      Base_Apply_MoneyType_List: [],
      // 活动类型集合
      Base_Apply_ActivityType_List: [],

      showCompanyPicker: false,
      companyIndex: -1,
      disableCompany: false,

      showAreaPicker: false,
      areaIndex: -1,
      disableArea: false,

      showVillageAreaPicker: false,
      villageAreaIndex: -1,
      disableVillageArea: false,

      projectIndex: 0,
      swiperIndex: 0,

      showSupportPopup: false,

      supportPackageList: [],
      supportPopupTitle: '',

      //
      form: {
        // 1.新增 2.编辑 3.追加
        PostType: 1,
        VId: 0,
        Year: 0,
        MonthId: '',
        Title: '',
        CompanyId: '',
        CompanyName: '',
        Region_AreaId: '',
        Village_AreaId: '',
        Region_Area: '',
        Village_Area: '',
        ApplyManagerId: '',
        ApplyManagerName: '',
        ApplyType: 1, //公司人员申请
        Remark: '',
        DetailList: []
      }
    };
  },

  onLoad(options) {
    if (options.Id) {
      this.form.VId = options.Id;
    }

    if (options.PostType) {
      this.form.PostType = options.PostType;
    }

    // if (this.form.PostType == 1) {
    this.form.ApplyManagerId = this.vuex_user.ManagerId;
    this.form.ApplyManagerName = this.vuex_user.Name;
    // }

    if (this.form.PostType == 2) {
      this.title = '预测申报编辑';
    }

    if (this.form.PostType == 3) {
      this.title = '预测申报追加';
    }

    uni.setNavigationBarTitle({
      title: this.title
    });

    if (options.DetailId) {
      this.DetailId = options.DetailId;
    }

    const now = new Date();
    const month = now.getMonth();

    this.quarter = this.quarterMap[parseInt((month + 3) / 3)];

    this.form.MonthId = month + 1;

    this.form.Year = now.getFullYear();

    this.getData();

    this.getBrandList();
  },

  methods: {
    loadMoneyTypeList() {
      this.$u.api.getMoneyTypeList().then(res => {
        console.log(res);
      });
    },

    handleExpectProjectAdd(item) {
      let len = item.HopeList.length;

      item.HopeList.push({
        Key: '',
        Value: '',
        RowsId: len + 1
      });
    },

    handleBrandChange(e, item) {
      let brand = this.Base_Brand_List.find(item => item.Key == e);
    },

    getBrandList() {
      this.$u.api.getMarketBrandList().then(res => {
        const { ResultCode, List } = res;
        if (ResultCode == 1) {
          this.Base_Brand_List = List;
        }
      });
    },

    handleSupportClick(item) {
      this.showSupportPopup = true;
      this.supportPopupTitle = item.ObjectName;

      this.getSupportPackageList(item.ObjectId);
    },

    getSupportPackageList(id) {
      this.$u.api
        .getSupportPackageList({
          Id: id
        })
        .then(res => {
          console.log(res);
          const { ResultCode, List } = res;
          if (ResultCode == 1) {
            this.supportPackageList = List;
          }
        });
    },

    handleOtherSupportChange(e, item) {
      e.forEach(s => {
        let index = item.OtherSupper_List.findIndex(o => o.ObjectId == s);

        if (index == -1) {
          let support = item.Base_Apply_OtherSupper_List.find(ba => ba.Key == s);

          item.OtherSupper_List.push({
            RowsId: 0,
            ObjectId: s,
            ObjectType: 5,
            ObjectName: support.Value,
            SetNumber: support.SetNumber ? support.SetNumber : 1
          });
        }
      });

      item.OtherSupper_List = item.OtherSupper_List.filter(support => e.includes(support.ObjectId));
    },

    handleCityChange(e, item) {
      item.ProvinceId = e.province.value;
      item.CityId = e.city.value;
      item.DistrictId = e.area.value;
    },

    onFirstDealerChange(e, item) {
      item.FirstDealerId = e[0];
    },

    onSecondDealerChange(e, item) {
      item.DoubleDealerId = e.secondDealerId;
    },

    onStoreDealerChange(e, item) {
      item.DoorDealerId = e;
    },

    onWayTypeChange(e) {
      let selected = {};

      if (e[0].label && e[0].value) {
        selected = e[0];
      } else {
        selected.label = this.Base_Apply_WaysType_List[0].Value;
        selected.value = this.Base_Apply_WaysType_List[0].Key;
      }

      this.form.DetailList[this.projectIndex].WaysType = selected.value;

      let index = this.Base_Apply_WaysType_List.findIndex(item => item.Key == selected.value);
      this.form.DetailList[this.projectIndex].wayTypeIndex = index;

      this.form.DetailList[this.projectIndex].moneyTypeIndex = -1;
      this.form.DetailList[this.projectIndex].activityTypeIndex = -1;
    },

    onMoneyTypeChange(e) {
      let selected = {};

      if (e[0].label && e[0].value) {
        selected = e[0];
      } else {
        selected.label = this.moneyTypeList[0].Value;
        selected.value = this.moneyTypeList[0].Key;
      }

      this.form.DetailList[this.projectIndex].MoneyType = selected.value;

      let index = this.moneyTypeList.findIndex(item => item.Key == selected.value);
      this.form.DetailList[this.projectIndex].moneyTypeIndex = index;

      this.form.DetailList[this.projectIndex].activityTypeIndex = -1;
    },

    onActivityTypeChange(e) {
      let selected = {};

      if (e[0].label && e[0].value) {
        selected = e[0];
      } else {
        selected.label = this.activityTypeList[0].Value;
        selected.value = this.activityTypeList[0].Key;
      }

      this.form.DetailList[this.projectIndex].ActivityType = selected.value;

      let index = this.activityTypeList.findIndex(item => item.Key == selected.value);
      this.form.DetailList[this.projectIndex].activityTypeIndex = index;
    },

    handleStartTimeChange(e, item) {
      item.StartTime_Str = e.result;
      item.StartTime = getTimeByDateString(e.result) / 1000;
    },

    handleEndTimeChange(e, item) {
      item.EndTime_Str = e.result;
      item.EndTime = getTimeByDateString(e.result) / 1000;
    },

    handleProjectChange(index) {
      this.swiperIndex = index;
    },

    transition(e) {
      if (this.form.PostType != 3) {
        let dx = e.detail.dx;
        this.$refs.uTabs.setDx(dx);
      }
    },
    // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
    // swiper滑动结束，分别设置tabs和swiper的状态
    animationfinish(e) {
      let current = e.detail.current;

      if (this.form.PostType == 1 || this.form.PostType == 2) {
        this.$refs.uTabs.setFinishCurrent(current);
      }
      this.projectIndex = current;
      this.swiperIndex = current;
    },

    handleDeleteClick(index) {
      this.showConfirm = true;
    },

    handleDeleteProject() {
      this.form.DetailList.splice(this.projectIndex, 1);
      this.showConfirm = false;

      if (this.projectIndex > 0) {
        this.projectIndex -= 1;
        this.swiperIndex -= 1;
      }
    },

    addProject() {
      let len = this.form.DetailList ? this.form.DetailList.length : 0;

      this.form.DetailList.push({
        tab_name: '项目' + (len + 1),

        showStart: false,
        showEnd: false,

        showWayTypePicker: false,
        wayTypeIndex: -1,

        showMoneyTypePicker: false,
        moneyTypeIndex: -1,

        showActivityTypePicker: false,
        activityTypeIndex: -1,

        areaCode: [],

        showSupport: false,

        Base_Apply_OtherSupper_List: JSON.parse(JSON.stringify(this.Base_Apply_OtherSupper_List)),

        Base_Brand_List: JSON.parse(JSON.stringify(this.Base_Brand_List)),

        VId: this.form.VId,
        DetailId: 0,
        Year: 0,
        Title: '',
        CompanyId: this.form.CompanyId,
        StartTime: '',
        EndTime: '',
        WaysType: 0,
        MoneyType: 0,
        ActivityType: 0,
        Remark: '',
        ProvinceId: '',
        CityId: '',
        DistrictId: '',
        Address: '',
        ObjectTypeId: '',
        ObjectOther: '',
        FirstDealerId: '',
        DoubleDealerId: '',
        DoorDealerId: '',
        Brand: '',
        Position: '',
        Mode: '',
        ApplySupport: '',
        ApplyReason: '',
        BDRCost: '',
        FirstCost: '',
        DoubleCost: '',
        DoorCost: 0, // $("#apply_DoorCost_" + that_index).val(),
        RemoveCost: '',
        IsDeviation: '',
        IsExceed: '',
        ActualCost: '',
        CheckCost: '',

        WaysType_List: [], //参与方式
        MoneyType_List: [], //费用类型
        ActivityType_List: [], //活动类型
        Brand_List: [], //品牌
        OtherSupper_List: [], //其他支持 选择集合
        Hope_Project_List: [], //期望项目
        Hope_Value_List: [], //期望效果
        HopeList: [],
        CheckList: [], //核销信息
        CheckInfo: {
          Id: '',
          CheckCost: '',
          State: 0,
          AuditRemark: '',
          TypeExtend_CheckList: []
        },
        ImplemenInfo: {
          VId: this.form.VId,
          DetailId: this.form.DetailId,
          IsDeviation: '',
          IsExceed: '',
          ActualCost: ''
        }
      });

      this.swiperIndex = len;
      this.projectIndex = len;
    },
    change(index) {
      this.navIndex = index;
    },
    changePro(index) {
      this.proIndex = index;
    },

    getCompanyChildren(parentId, level) {
      this.$u.api
        .getCompanyChildrenList({
          ParentId: parentId
        })
        .then(res => {
          const { ResultCode, ResultMessage, List } = res;
          console.log(res);
          if (ResultCode == 1) {
            if (level == 2) {
              this.Base_Apply_Region_AreaList = List;
            }

            if (level == 3) {
              this.Base_Apply_Village_AreaList = List;
            }
          }
        });
    },

    onCompanyChange(e) {
      let selected = {};

      if (e[0].label && e[0].value) {
        selected.value = e[0].value;
        selected.label = e[0].label;
      } else {
        if (this.Base_Apply_BudGetList.length > 0) {
          selected.value = this.Base_Apply_BudGetList[0].Key;
          selected.label = this.Base_Apply_BudGetList[0].Value;
        }
      }

      this.form.CompanyId = selected.value;
      this.form.CompanyName = selected.label;

      this.companyIndex = this.Base_Apply_BudGetList.findIndex(item => item.Key == this.form.CompanyId);

      this.resetTypes();
      this.getAllTypeList(this.form.CompanyId);

      this.getCompanyChildren(this.form.CompanyId, 2);
    },

    resetTypes() {
      this.areaIndex = -1;
      this.villageAreaIndex = -1;

      this.Region_AreaId = '';
      this.Village_AreaId = '';
      this.Region_Area = '';
      this.Village_Area = '';

      this.form.DetailList.forEach(item => {
        item.wayTypeIndex = -1;
        item.moneyTypeIndex = -1;
        item.activityTypeIndex = -1;
        item.WaysType = 0;
        item.MoneyType = 0;
        item.ActivityType = 0;

        item.WaysType_List = [];
        item.MoneyType_List = [];
        item.ActivityType_List = [];

        item.OtherSupper_List = [];
      });
    },

    getAllTypeList(id) {
      const now = new Date();
      const month = now.getMonth();

      this.$u.api
        .getMarketAllTypeList({
          Year: this.form.Year,
          ObjectId: id,
          QuarterId: parseInt((month + 3) / 3)
        })
        .then(res => {
          const {
            ResultCode,
            Base_Apply_WaysType_List,
            Base_Apply_Region_AreaList,
            Base_Apply_Village_AreaList,
            Base_Apply_MoneyType_List,
            Base_Apply_ActivityType_List,
            Base_Apply_OtherSupper_List
          } = res;

          if (ResultCode == 1) {
            // if (Base_Apply_Region_AreaList) {
            //   this.Base_Apply_Region_AreaList = Base_Apply_Region_AreaList;
            // }

            // if (Base_Apply_Village_AreaList) {
            //   this.Base_Apply_Village_AreaList = Base_Apply_Village_AreaList;
            // }

            if (Base_Apply_WaysType_List) {
              this.Base_Apply_WaysType_List = Base_Apply_WaysType_List;
            }

            if (Base_Apply_MoneyType_List) {
              this.Base_Apply_MoneyType_List = Base_Apply_MoneyType_List;
            }

            if (Base_Apply_ActivityType_List) {
              this.Base_Apply_ActivityType_List = Base_Apply_ActivityType_List;
            }

            if (Base_Apply_OtherSupper_List) {
              Base_Apply_OtherSupper_List.forEach(item => {
                this.$set(item, 'checked', false);
              });

              this.Base_Apply_OtherSupper_List = Base_Apply_OtherSupper_List;

              this.form.DetailList.forEach(item => {
                item.Base_Apply_OtherSupper_List = JSON.parse(JSON.stringify(Base_Apply_OtherSupper_List));
              });
            }
          }
        });
    },

    onAreaChange(e) {
      let selected = {};

      if (e[0].label && e[0].value) {
        selected.value = e[0].value;
        selected.label = e[0].label;
      } else {
        if (this.Base_Apply_Region_AreaList.length > 0) {
          selected.value = this.Base_Apply_Region_AreaList[0].Key;
          selected.label = this.Base_Apply_Region_AreaList[0].Value;
        }
      }

      this.form.Region_AreaId = selected.value;
      this.form.Region_Area = selected.label;

      this.areaIndex = this.Base_Apply_Region_AreaList.findIndex(item => item.Key == this.form.Region_AreaId);

      this.getCompanyChildren(this.form.Region_AreaId, '3');
    },

    onVillageAreaChange(e) {
      let selected = {};

      if (e[0].label && e[0].value) {
        selected.value = e[0].value;
        selected.label = e[0].label;
      } else {
        if (this.Base_Apply_Village_AreaList.length > 0) {
          selected.value = this.Base_Apply_Village_AreaList[0].Key;
          selected.label = this.Base_Apply_Village_AreaList[0].Value;
        }
      }

      this.form.Village_AreaId = selected.value;
      this.form.Village_Area = selected.label;

      this.villageAreaIndex = this.Base_Apply_Village_AreaList.findIndex(item => item.Key == this.form.Village_AreaId);
    },

    handleCommit() {
      this.form.DetailList.forEach(item => {
        item.DetailId = item.Id;
        item.CompanyId = this.form.CompanyId;

        let waysType = this.Base_Apply_WaysType_List.find(w => w.Key == item.WaysType);
        if (waysType) {
          item.WaysType_List = [
            {
              RowsId: 1,
              ObjectId: waysType.Key,
              ObjectType: 1,
              ObjectName: waysType.Value
            }
          ];
        }

        let moneyType = this.Base_Apply_MoneyType_List.find(m => m.Key == item.MoneyType);

        if (moneyType) {
          item.MoneyType_List = [
            {
              RowsId: 1,
              ObjectId: moneyType.Key,
              ObjectType: 2,
              ObjectName: moneyType.Value
            }
          ];
        }

        let activityType = this.Base_Apply_ActivityType_List.find(a => a.Key == item.ActivityType);
        if (activityType) {
          item.ActivityType_List = [
            {
              RowsId: 1,
              ObjectId: activityType.Key,
              ObjectType: 3,
              ObjectName: activityType.Value
            }
          ];
        }

        let brand = item.Base_Brand_List.find(b => b.Value == item.Brand);
        if (brand) {
          item.Brand_List = [
            {
              ObjectId: brand.Key,
              ObjectType: 4,
              ObjectName: brand.Value
            }
          ];
        }
      });

      if (this.form.PostType == 1) {
        this.$u.api.savePrediction(this.form).then(res => {
          const { ResultCode, ResultMessage } = res;

          if (ResultCode == 1) {
            this.$refs.uToast.show({
              title: ResultMessage,
              callback() {
                let pages = getCurrentPages(); // 当前页面
                let beforePage = pages[pages.length - 2]; //

                uni.navigateBack({
                  success: function() {
                    if (beforePage) {
                      beforePage.getData(true); // 执行上一页的onLoad方法
                    }
                  }
                });
              }
            });
          } else {
            this.$u.toast(ResultMessage);
          }
        });
      } else {
        this.$u.api.updatePrediction(this.form).then(res => {
          const { ResultCode, ResultMessage } = res;

          if (ResultCode == 1) {
            this.$refs.uToast.show({
              title: ResultMessage,
              callback() {
                let pages = getCurrentPages(); // 当前页面
                let beforePage = pages[pages.length - 2]; //

                uni.navigateBack({
                  success: function() {
                    if (beforePage) {
                      beforePage.getData(true); // 执行上一页的onLoad方法
                    }
                  }
                });
              }
            });
          } else {
            this.$u.toast(ResultMessage);
          }
        });
      }
    },

    getData() {
      this.$u.api
        .getPredictionDetail({
          VId: this.form.VId,
          detailId: this.DetailId
        })
        .then(res => {
          console.log(res);
          const {
            Base_Apply_ActivityType_List,
            Base_Apply_BudGetList,
            Base_Apply_MoneyType_List,
            Base_Apply_OtherSupper_List,
            Base_Apply_Region_AreaList,
            Base_Apply_Village_AreaList,
            Base_Apply_WaysType_List,
            Base_FirstDealer_List,
            CompanyId,
            Perject_Body,
            Perject_Content,
            Region_AreaId,
            ResultCode,
            ResultMessage,
            Village_AreaId
          } = res;

          if (ResultCode == 1) {
            if (Perject_Body) {
              this.form.Title = Perject_Body.Title;
              this.form.Remark = Perject_Body.Remark;
              this.form.ApplyManagerName = Perject_Body.ApplyManagerName;
              this.form.Year = Perject_Body.Year;
              this.form.MonthId = Perject_Body.MonthId;

              let companyIndex = Base_Apply_BudGetList.findIndex(item => item.Key == Perject_Body.CompanyId);

              this.companyIndex = companyIndex;

              if (companyIndex > -1) {
                this.form.CompanyName = Base_Apply_BudGetList[companyIndex].Value;
                this.form.CompanyId = Base_Apply_BudGetList[companyIndex].Key;
              }

              let regionAreaIndex = Base_Apply_Region_AreaList.findIndex(
                item => item.Key == Perject_Body.Region_AreaId
              );
              this.regionAreaIndex = regionAreaIndex;

              if (regionAreaIndex > -1) {
                this.form.Region_AreaId = Base_Apply_Region_AreaList[regionAreaIndex].Key;
                this.form.Region_Area = Base_Apply_Region_AreaList[regionAreaIndex].Value;
              }

              let villageAreaIndex = Base_Apply_Village_AreaList.findIndex(
                item => item.Key == Perject_Body.Village_AreaId
              );

              this.villageAreaIndex = villageAreaIndex;

              if (villageAreaIndex > -1) {
                this.form.Village_AreaId = Base_Apply_Village_AreaList[villageAreaIndex].Key;
                this.form.Village_Area = Base_Apply_Village_AreaList[villageAreaIndex].Value;
              }
            }

            if (Base_Apply_BudGetList) {
              this.Base_Apply_BudGetList = Base_Apply_BudGetList;

              if (this.form.PostType == 1) {
                if (CompanyId && CompanyId != 0) {
                  this.disableCompany = true;

                  let companyIndex = Base_Apply_BudGetList.findIndex(item => item.Key == CompanyId);

                  if (companyIndex > -1) {
                    this.form.CompanyId = Base_Apply_BudGetList[companyIndex].Key;
                    this.form.CompanyName = Base_Apply_BudGetList[companyIndex].Value;
                    this.companyIndex = companyIndex;
                  }
                }
              }
            }

            if (Base_Apply_Region_AreaList) {
              this.Base_Apply_Region_AreaList = Base_Apply_Region_AreaList;

              if (this.form.PostType == 1) {
                if (Region_AreaId && Region_AreaId != 0) {
                  this.disableArea = true;

                  let areaIndex = Base_Apply_Region_AreaList.findIndex(item => item.Key == Region_AreaId);
                  if (areaIndex > -1) {
                    this.form.Region_AreaId = Base_Apply_Region_AreaList[areaIndex].Key;
                    this.form.Region_Area = Base_Apply_Region_AreaList[areaIndex].Value;
                    this.areaIndex = areaIndex;
                  }
                }
              }
            }

            if (Base_Apply_Village_AreaList) {
              this.Base_Apply_Village_AreaList = Base_Apply_Village_AreaList;

              if (this.form.PostType == 1) {
                if (Village_AreaId && Village_AreaId != 0) {
                  this.disableVillageArea = true;

                  let areaIndex = Base_Apply_Village_AreaList.findIndex(item => item.Key == Village_AreaId);
                  if (areaIndex > -1) {
                    this.form.Village_AreaId = Base_Apply_Village_AreaList[areaIndex].Key;
                    this.form.Village_Area = Base_Apply_Village_AreaList[areaIndex].Value;
                    this.villageAreaIndex = areaIndex;
                  }
                }
              }
            }

            if (Base_Apply_WaysType_List) {
              this.Base_Apply_WaysType_List = Base_Apply_WaysType_List;
            }

            if (Base_Apply_MoneyType_List) {
              this.Base_Apply_MoneyType_List = Base_Apply_MoneyType_List;
            }

            if (Base_Apply_ActivityType_List) {
              this.Base_Apply_ActivityType_List = Base_Apply_ActivityType_List;
            }

            if (Base_Apply_OtherSupper_List) {
              Base_Apply_OtherSupper_List.forEach(item => {
                this.$set(item, 'checked', false);
              });
              this.Base_Apply_OtherSupper_List = Base_Apply_OtherSupper_List;
            }

            if (this.form.PostType != 3) {
              if (Perject_Content) {
                this.form.DetailList = Perject_Content.map(item => {
                  item.Perject_Detail.BrandList = item.BrandList;
                  item.Perject_Detail.HopeList = item.HopeList;

                  item.Perject_Detail._OtherSupportList = item.OtherSupportList;

                  return item.Perject_Detail;
                });

                this.form.DetailList.forEach((item, index) => {
                  item.tab_name = '项目' + (index + 1);

                  this.$set(item, 'showStart', false);
                  this.$set(item, 'showEnd', false);

                  this.$set(item, 'showWayTypePicker', false);

                  let wayTypeIndex = this.waysTypeList.findIndex(w => w.Key == item.WaysType);
                  this.$set(item, 'wayTypeIndex', wayTypeIndex);

                  this.$set(item, 'showMoneyTypePicker', false);

                  let moneyTypeList = this.Base_Apply_MoneyType_List.filter(m => m.ParentId == item.WaysType);
                  let moneyTypeIndex = moneyTypeList.findIndex(m => m.Key == item.MoneyType);
                  this.$set(item, 'moneyTypeIndex', moneyTypeIndex);

                  this.$set(item, 'showActivityTypePicker', false);

                  let activityTypeList = this.Base_Apply_ActivityType_List.filter(m => m.ParentId == item.MoneyType);
                  let activityTypeIndex = activityTypeList.findIndex(a => a.Key == item.ActivityType);
                  this.$set(item, 'activityTypeIndex', activityTypeIndex);

                  this.$set(item, 'areaCode', [item.ProvinceId, item.CityId, item.DistrictId]);

                  this.$set(item, 'showSupport', false);

                  this.$set(
                    item,
                    'Base_Apply_OtherSupper_List',
                    JSON.parse(JSON.stringify(this.Base_Apply_OtherSupper_List))
                  );

                  this.$set(item, 'Base_Brand_List', JSON.parse(JSON.stringify(this.Base_Brand_List)));

                  item.StartTime_Str = this.$u.timeFormat(item.StartTime, 'yyyy-mm-dd');
                  item.EndTime_Str = this.$u.timeFormat(item.EndTime, 'yyyy-mm-dd');

                  if (item.BrandList && item.BrandList.length > 0) {
                    this.$set(item, 'Brand', item.BrandList[0].Value);
                  }

                  item.Base_Apply_OtherSupper_List.forEach(s => {
                    let index = item._OtherSupportList.findIndex(o => o.Key == s.Key);
                    if (index > -1) {
                      this.$set(s, 'SetNumber', item._OtherSupportList[index].IsShow);
                    } else {
                      this.$set(s, 'SetNumber', 1);
                    }
                    this.$set(s, 'checked', index > -1);
                  });

                  let otherSupportList = item.Base_Apply_OtherSupper_List.filter(s => s.checked).map(s => {
                    return {
                      RowsId: 0,
                      ObjectId: s.Key,
                      ObjectType: 5,
                      ObjectName: s.Value,
                      SetNumber: s.SetNumber
                    };
                  });

                  this.$set(item, 'OtherSupper_List', otherSupportList);
                });

                if (this.form.PostType != 3) {
                  this.$refs.uTabs.setFinishCurrent(0);
                  this.projectIndex = 0;
                  this.swiperIndex = 0;
                }

                console.log(this.form);
              }
            } else {
              this.addProject();
            }
          }
        });
    }
  },

  computed: {
    waysTypeList() {
      return this.Base_Apply_WaysType_List;
    },

    moneyTypeList() {
      if (this.form.DetailList.length > 0) {
        let parentId = this.form.DetailList[this.projectIndex].WaysType;

        if (parentId > -1) {
          return this.Base_Apply_MoneyType_List.filter(item => item.ParentId == parentId);
        }
      }

      return this.Base_Apply_MoneyType_List;
    },

    activityTypeList() {
      if (this.form.DetailList.length > 0) {
        let parentId = this.form.DetailList[this.projectIndex].MoneyType;

        if (parentId > -1) {
          return this.Base_Apply_ActivityType_List.filter(item => item.ParentId == parentId);
        }
      }

      return this.Base_Apply_ActivityType_List;
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/.u-collapse-head {
  padding-bottom: 0px;
}
/deep/.u-collapse-title {
  color: #ff7626;
}
/deep/.u-collapse-body {
  overflow: auto !important;
}

.dealer-select {
  /deep/.u-drawer-bottom {
    bottom: 200rpx !important;
  }
}

/deep/.u-calendar {
  margin-bottom: 320rpx;
}

/deep/.u-collapse-title {
  text-align: right !important;
  height: 80rpx;
  line-height: 80rpx;
}

.current0,
.current1 {
  height: calc(100vh - 300rpx);
  overflow-y: scroll;
  .current1-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .current1-title {
      display: flex;
      align-items: center;
      flex: 2;
      font-size: 36rpx;
      font-weight: bold;
      .line {
        display: inline-block;
        height: 36rpx;
        width: 6rpx;
        margin-right: 20rpx;
        background: #ff8441;
      }
    }
    .add-project {
      width: 140rpx;
      height: 50rpx;
      line-height: 50rpx;
      border-radius: 8rpx;
      background: #f47021;
      color: #fff;
      text-align: center;
    }
  }
  .current1-content {
    margin-bottom: 40rpx;
    margin-top: 30rpx;
    padding-bottom: 30rpx;
    border-radius: 8rpx;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.3);
    .form-wrap {
      padding: 20rpx 26rpx;
    }
    .open-info {
      display: flex;
      color: #f47021;
      justify-content: space-between;
    }
    .open-info-content {
      margin-left: 20rpx;
      margin-top: 20rpx;
      .info-title,
      .info-data {
        display: flex;
        align-items: center;
        margin: 10rpx 0;
      }
    }
  }
  .tabs-dmoe {
    font-size: 32rpx;
    display: flex;
    justify-content: flex-start;
    overflow-x: scroll;
    .tab-item {
      text-align: center;
      padding: 16rpx 20rpx 16rpx 20rpx;
      color: #707070;
      white-space: nowrap;
      /deep/.u-icon__icon {
        font-weight: bold !important;
      }
    }
    .tabActive {
      color: #f47021;
      font-weight: bold;
    }
  }
}
.tab-title {
  margin: 60rpx 0 20rpx 0;
  display: inline-block;
  color: #f47021;
  font-size: 32rpx;
  font-weight: bold;
  padding-bottom: 10rpx;
  border-bottom: 4rpx solid #f47021;
}
/deep/.u-form-item {
  padding: 10rpx 0;
}

.project-wrapper {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100rpx);
  width: 100%;
}

.swiper-box {
  flex: 1;
}

.swiper-item {
  height: 100%;
}

.delete-project {
  width: 140rpx;
  height: 50rpx;
  line-height: 50rpx;
  border-radius: 8rpx;
  background: #ea4300;
  color: #fff;
  text-align: center;
}
</style>
